package com.imufe.chemicalenterprisedangerwarning.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author BaiBan
 * @since 2022/10/13
 */
@Log4j2
public class JwtUtil {

    // 有效期为 60 * 60 * 1000 一个小时
    public static final Long JWT_TTL = 60 * 60 * 1000L;

    // 设置密匙明文
    public static final String JWT_KEY = "leetcode";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * ⽣成 jwt
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        log.info(builder);
        return builder.compact();
    }

    /**
     * ⽣成 jwt
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 创建 token
     */
    public static String createJWT(String subject, Long ttlMillis, String id) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {

        if (ttlMillis == null)
            ttlMillis = JwtUtil.JWT_TTL;

        // 当前时间时间戳
        long nowMillis = System.currentTimeMillis();

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setId(uuid) // 唯⼀ id
                .setSubject(subject) // 主题 可以是 JSON 数据
                .setIssuedAt(new Date(nowMillis)) // 签发时间
                .signWith(SignatureAlgorithm.HS256, generalKey()) //使用 HS256 对称加密算法签名, 第二个参数为秘钥
                .setExpiration(new Date(nowMillis + ttlMillis));
    }

    /**
     * ⽣成加密后的秘钥 secretKey
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 解析JWT
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
}